package servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import service.PositionService;

/**
 * Servlet implementation class PdfDownloadServlet
 */
@WebServlet("/PdfDownloadServlet")
public class PdfDownloadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	@EJB PositionService positionService; 
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public PdfDownloadServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		byte [] pdf=null;
		if (request.getParameter("expType").equals("1"))
			pdf=exportPosition(request, response);
		else if (request.getParameter("expType").equals("2")){
			pdf=exportPositionAndCandidates(request, response);
		}
		if(pdf.length!=0){
			ServletOutputStream outStream = response.getOutputStream();
			response.setContentType("pdf");
			response.setContentLength(pdf.length);
			response.setHeader("Content-Disposition", "attachment; filename=\"" + "pdf" + "\"");

			outStream.write(pdf, 0,pdf.length);
		}

	}


	public byte[] exportPosition(HttpServletRequest request,
			HttpServletResponse response) {
		int idp=Integer.parseInt(request.getParameter("idPosition"));
		return positionService.exportPosition(idp);
	}

	public byte[] exportPositionAndCandidates(HttpServletRequest request,
			HttpServletResponse response) {
		int idp=Integer.parseInt(request.getParameter("idPosition"));
		return positionService.exportPositionAndCandidates(idp);
	}

}
